package com.example.testproj.file;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.testproj.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RandomAccessFileActivity extends AppCompatActivity {
    private static final String TAG = "RandomAccessFileActivit";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_random_access_file);
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(randomTest);
    }

    private Runnable randomTest = new Runnable() {
        @Override
        public void run() {
            try {
                File file = new File(Environment.getExternalStorageDirectory() + "/test2.txt");
                if (!file.exists()) {
                    initialWrite(file);
                }
                readFile(file);
                readFile(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void readFile(File file) throws IOException {
        RandomAccessFile randomAccessFile=new RandomAccessFile(file,"rw");
        int counter=randomAccessFile.readInt();
        String msg=randomAccessFile.readUTF();

        Log.d(TAG, "readFile: counter"+counter);
        Log.d(TAG, "readFile: msg"+msg);

        incrementReadCounter(randomAccessFile);

        randomAccessFile.close();
    }

    private void incrementReadCounter(RandomAccessFile randomAccessFile) throws IOException {
        long currentPos=randomAccessFile.getFilePointer();
        randomAccessFile.seek(0);
        int counter=randomAccessFile.readInt();
        counter++;
        Log.d(TAG, "incrementReadCounter: "+counter);
        randomAccessFile.seek(0);
        randomAccessFile.writeInt(counter);
        randomAccessFile.seek(currentPos);
    }

    private void initialWrite(File file) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        randomAccessFile.writeInt(0);
        randomAccessFile.writeUTF("hello world!");
        randomAccessFile.close();
    }
}
